<script setup lang="ts">
import { ref, reactive } from 'vue';
import { back, homePage } from '@/hooks/index'
import { useUserStore } from '@/store/user'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
const userStore = useUserStore()
// 登录表单信息
const userForm = reactive<User.UserForm>({
  username: '',
  password: '',
})
// 表单实例
const ruleFormRef = ref<FormInstance>()
// 表单验证规则
const rulesFrom = reactive<FormRules<typeof userForm>>({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
})

// 登入
function onSubmit(formEl: FormInstance | undefined): void {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      const userInfo: User.UserStoreInfo | undefined = userStore.login(userForm)
      if(userInfo === undefined) {
        ElMessage.error('用户名或密码错误~')
        return
      }
      userStore.setUser(userInfo) // 登录成功，存储用户信息
      homePage() // 回到首页
    }
  })
}
</script>
<template>
  <div class="title">登录</div>
  <div class="formInfo">
    <el-form ref="ruleFormRef" :model="userForm" :rules="rulesFrom" label-width="120px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="userForm.username" placeholder="请输入用户名" maxlength="15" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="userForm.password" placeholder="请输入密码" maxlength="20" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit(ruleFormRef)">登入</el-button>
        <el-button @click="back">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<style lang="scss" scoped>
.title {
  width: 100%;
  text-align: center;
  margin: 40px auto;
  font-size: 30px;
}
.formInfo {
  width: 500px;
  margin: 20px auto 0;
}
</style>